module(..., package.seeall)
--[[

===========================================================
Author: Osvaldo Ros (osvaldo@splosive.com)

Copyright (C) 2011 by Splosive Labs (www.splosive.com)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN

===========================================================
]]



--[[
================================================
Main package 

 - This library contains the core classes that conform the RDX framework. Of all these classes the most important by far is the View class. To use RDX your lua files
   must extend the View class and provide an implementation of the getLayout method and call the init() method OR alternatively use the remoteInit with the path of the
   external JSON file to use.

================================================
]]
	


local package = function()


	local self = {}
	

	--[[
	================================================
	EXTERNAL DEPENDENCIES

	-- * IMPORTANT This uses the external modules required below. Because of the way Corona SDK works, these files must be in the same folder as your
     project. To keep this separated from your project you can also create a symbolic link in your folder pointing to these files 
	================================================
	]]
	
	local dataDumper = require("Datadumper")
	local physics = require("physics")
	local sprite = require ("sprite")
	local Class = require("RDX_Class")
	local JSON = require("JSON")
	

	--[[
	================================================
	Config Class
	================================================
	]]
	
	local Config = function(target)
	
		local public = {}
		local protected = {}
		local StringUtils = self.StringUtils
		
		local super = Class.buildClass(target, public, protected)
		-- this is what makes the whole thing work, methods access 'this' which points to the sub class 'private', if an implementation is not found there, then
		-- it will go up to the base class
		local this = protected
		-- same goes for the public, we should always access public through api, this way it will look in the subclass first and then the super class
		local api = public
		
		protected.behaviorPackages = {}
		protected.objectPackages = {}
		public.events = {
			touch="touch", press="touch", click="touch", release="touch",
			collision="collision",
			preCollision="preCollision", precollision="preCollision",
			postCollision="postCollision", postcollision="postCollision"
		}
		
		
		public.remoteViewsBasePath = nil
		public.traceLevel = "ALL"
		
		protected.init = function()
			public.registerBehaviors("RDX_Behaviors")
			public.registerObjects("RDX_Objects")
		end
		
		public.registerBehaviors = function(path)
			this.behaviorPackages[#this.behaviorPackages + 1] = require(path)
		end
		
		public.registerObjects = function(path)
			this.objectPackages[#this.objectPackages + 1] = require(path)
		end
		
		public.getBehavior = function(name)
			
			local errorMessage
			
			for k,packageContainer in ipairs(this.behaviorPackages) do
		
				local typeParts = StringUtils.split(name, ".")
				local currentObj = nil
				local currenPath = ""
				local displayDivider = ""
				
				for k,v in pairs(typeParts) do
					com.splosive.trace("getBehavior > " ..v, "View-Get-Behavior")
					if(currentObj ~= nil)then
						com.splosive.trace("getBehavior > currentObj exist", "View-Get-Behavior")
						if(currentObj[v] ~= nil)then
							com.splosive.trace("getBehavior > ".. v .." exists in currentObj", "View-Get-Behavior")
							currentObj = currentObj[v]
						else
							currentObj = nil
							errorMessage = "getBehavior > Unable to find " .. v .. " in " .. currenPath
						end
					else
						currentObj = packageContainer[v]
						if(currentObj)then
							com.splosive.trace("getBehavior > ".. v .." is a function", "View-Get-Behavior")
							
							if(type(currentObj) == "function")then
								com.splosive.trace("getBehavior > ".. v .." is a function", "View-Get-Behavior")
								currentObj = currentObj()
							end
						else
							errorMessage = "getBehavior > Unable to find package " .. v .. " in registered behaviors"
							break
						end
					end
					
					currenPath = currenPath .. displayDivider .. v
					displayDivider = "."
					
				end
				
				if(currentObj)then
					return currentObj
				end
			
			end
			
			if(errorMessage)then
				error(errorMessage)
			else
				error("getBehavior > Unable to find behavior " .. name)
			end
			return nil
			
		end
		
		
		public.getObjectFactory = function(context)
			local errorMessage
			
			local name = context.descriptor.type
		
			for k,packageContainer in ipairs(this.objectPackages) do
		
				local typeParts = StringUtils.split(name, ".")
				local currentObj = nil
				local currenPath = ""
				local displayDivider = ""
				
				for k,v in pairs(typeParts) do
					com.splosive.trace("getObjectFactory > " ..v, "View-Get-Object")
					if(currentObj ~= nil)then
						com.splosive.trace("getObjectFactory > currentObj exist", "View-Get-Object")
						if(currentObj[v] ~= nil)then
							com.splosive.trace("getObjectFactory > ".. v .." exists in currentObj", "View-Get-Object")
							currentObj = currentObj[v]
						else
							currentObj = nil
							errorMessage = "getObjectFactory > Unable to find " .. v .. " in " .. currenPath
						end
					else
						currentObj = packageContainer[v]
						if(currentObj)then
							com.splosive.trace("getObjectFactory > ".. v .." is a function", "View-Get-Object")
							
							if(type(currentObj) == "function")then
								com.splosive.trace("getObjectFactory > ".. v .." is a function", "View-Get-Object")
								currentObj = currentObj()
							end
						else
							errorMessage = "getObjectFactory > Unable to find package " .. v .. " in registered objects"
							break
						end
					end
					
					currenPath = currenPath .. displayDivider .. v
					displayDivider = "."
					
				end
				
				if(currentObj)then
					return currentObj(context)
				end
			
			end
			
			if(errorMessage)then
				error(errorMessage)
			else
				error("getObjectFactory > Unable to find object " .. name)
			end
			return nil
			
		end
		
		
		public.behaviorEvents = function()
	
			-- this table is used to validate the name entered in the View declaration
			return {
				OBJECT_PRESS = true, 
				OBJECT_RELEASE = true, 
				COLLISION_BEGIN = true, 
				COLLISION_END = true
			}
			
		end
		
		this.init()
		
		
		return api
		
	end
	
	
	--[[
	================================================
	IO Class
	================================================
	]]
	
	local IO = function(target)
	
		local public = {}
		local protected = {}
		
		local super = Class.buildClass(target, public, protected)
		-- this is what makes the whole thing work, methods access 'this' which points to the sub class 'private', if an implementation is not found there, then
		-- it will go up to the base class
		local this = protected
		-- same goes for the public, we should always access public through api, this way it will look in the subclass first and then the super class
		local api = public
		
		
		public.readFile = function(fileName)
		
			local path = system.pathForFile( fileName, system.DocumentsDirectory )
			local file = io.open( path, "r" )
			local content
			if file then -- nil if no file found
			   content = file:read( "*a" )
			   io.close( file )
			end
			
			return content
		
		end
		
		public.writeFile = function(fileName, content)
		
	        local path = system.pathForFile( fileName, system.DocumentsDirectory )                
	        local file = io.open( path, "w+b" )
			-- Creates the file where we save our data if needed
	        
			file:write(content)          
	        io.close( file )
		
		end
		
		public.post = function(url, body)
			
			local function networkListener( event )
		        if ( event.isError ) then
	                com.splosive.trace( "Network error! Couldn't post " .. url, "Editor-Networking")
		        else
	                 com.splosive.trace ( url .. " =  " .. event.response, "Editor-Networking" )
		        end
			end
			
			local headers = { body = body}
			 
			network.request( url, "POST", networkListener, headers )
		
		
		end
		
		return api
		
	end
	
	
	
	--[[
	================================================
	dump function, uses the Datadumper to print a complex structure to the console
	================================================
	]]
	local dump = function(data)
		print(dataDumper.DataDumper(data))
	end
	
	
	
	--[[
	================================================
	trace function, use this instead of print to take advantage of filtering facilities
	================================================
	]]
	local trace = function(msg, filter)
		filter = filter or "ALL"
		local StringUtils = self.StringUtils
		
		local passFilter = true
		local filterParts = StringUtils.split(filter, "-")
		local levelParts = StringUtils.split(self.Config.traceLevel, "-")
		for k,wrapper in pairs(levelParts) do
		
			if(levelParts[k] == "nil")then
				if(filterParts[k] ~= nil)then
					passFilter = false
				end
			else
				if(levelParts[k] ~= filterParts[k])then
					passFilter = false
				end
			end
		end
		
		if(self.Config.traceLevel == "ALL" or passFilter)then
			--print("["..filter .."] >> " .. msg)
			io.write( "["..filter .."] >> " .. msg .. "\n" ) -- write the string to console
			io.flush()
		end
	end
	
	
	--[[
	================================================
	ViewManager Class, a barebones manager to switch views, invokes setup and cleanup methods
	================================================
	]]
	
	local ViewManager = function(target)
	
		local public = {}
		local protected = {}
		
		local super = Class.buildClass(target, public, protected)
		-- this is what makes the whole thing work, methods access 'this' which points to the sub class 'private', if an implementation is not found there, then
		-- it will go up to the base class
		local this = protected
		-- same goes for the public, we should always access public through api, this way it will look in the subclass first and then the super class
		local api = public
		
		this.currentView = nil
		this.lastViewName = nil
		this.lastParams = nil
		this.mainGroup = nil
		
		this.viewHistory = {}
		
		public.init = function(group)
			trace("ViewManager > init ", "ViewManager")
			this.mainGroup = group
			this.mainGroup.id = "stage"
		end
		
		
		public.resetView = function()
			trace("ViewManager > resetView ====================================", "ViewManager")
			 public.changeView(this.lastViewName, this.lastParams)
		end
		
		public.changeView = function(newViewName, params)
			trace("ViewManager > changeView to ============== " .. newViewName .. " ========================", "ViewManager")
			if(this.currentView ~= nil)then
				
				if(newViewName ~= this.lastViewName)then
					this.viewHistory[#this.viewHistory + 1] = {viewName = this.lastViewName, params = params }
				end
				
				this.currentView.clean()
				this.currentView.mainGroup:removeSelf()
				this.currentView.mainGroup = nil
			
				--if string.lower(this.lastViewName) == string.lower(newViewName) then
				 	--return true
				--end
				 
			end
			
			 
			local viewFile = require(newViewName)
			this.currentView = viewFile.getView(params)
			api.currentView = this.currentView
			this.lastViewName = newViewName
			this.lastParams = params
			 
			this.mainGroup:insert(this.currentView.mainGroup)
			trace("ViewManager > view inserted = ", "ViewManager")
		
		end
		
		public.changeToPreviousView = function()
			local previousViewInfo = this.viewHistory[#this.viewHistory]
			this.viewHistory[#this.viewHistory] = nil
			public.changeView(previousViewInfo.viewName, previousViewInfo.params)
		end
		
		
		return api
		
	end
	
	
	--[[
	================================================
	Camera Class
	================================================
	]]
	
	local Camera = function(target)
	
		local public = {}
		local protected = {}
		
		local super = Class.buildClass(target, public, protected)
		-- this is what makes the whole thing work, methods access 'this' which points to the sub class 'private', if an implementation is not found there, then
		-- it will go up to the base class
		local this = protected
		-- same goes for the public, we should always access public through api, this way it will look in the subclass first and then the super class
		local api = public
		
		this.containerGroup = nil
		protected.transitioning = false
		
		public.paddingLeft = 0
		public.paddingRight = 0
		public.paddingTop = 0
		public.paddingBottom = 0
		
		public.restrict = nil
		
		public.setContainer = function(container)
			trace("Setting containerGroup", "Camera")
			this.containerGroup = container
		end
		
		
		public.getX = function()
			return (this.containerGroup.x - display.contentWidth/2) * -1 
		end
		
		public.getY = function()
			return (this.containerGroup.y - display.contentHeight/2) * -1
		end
		
		public.getParent = function()
			return this.containerGroup
		end
		
		public.getParentEquivalent = function(camX, camY)
			local parentX
			local parentY
			
			if(camX)then
				parentX = ( camX - display.contentWidth/2 ) * -1
			end
			if(camY)then
				parentY = ( camY - display.contentHeight/2 ) * -1
			end
			
			return parentX, parentY
		end
		
		public.panBy = function(x, y)
		
			local newX
			local newY
		
			if(y ~= nil) then 
				newY = this.containerGroup.y + y 
			end
			if(x ~= nil) then 
				newX = this.containerGroup.x + x 
			end
			
			newX, newY = this.validatePosition(newX, newY)
			this.updateCamera(newX, newY)
			
		end
		
		public.panTo = function(x, y)
			trace("Camera > panTo", "Camera")
			local newX
			local newY
			
			if(y ~= nil) then 
				newY = -y + display.contentHeight/2 
				trace("Camera > panTo > newY = " .. newY, "Camera")
			end
			if(x ~= nil) then 
				newX = -x + display.contentWidth/2 
				trace("Camera > panTo > newX = " .. newX, "Camera")
			end
			
			newX, newY = this.validatePosition(newX, newY)
			
			this.updateCamera(newX, newY)
			
			--if(y ~= nil) then trace("Object y = " .. y .. "Container height = " .. this.containerGroup.height) end
		end
		
		
		
		public.smoothPanTo = function(x, y, delay)
			local newX
			local newY
			
			
			if(delay == nil)then
				delay = 500
			end
			
			if(protected.transitioning == false)then
			
				if(y ~= nil) then 
					newY = -y + display.contentHeight/2 
				end
				if(x ~= nil) then 
					newX = -x + display.contentWidth/2 
				end
				
				newX, newY = this.validatePosition(newX, newY)
					
				local transitionProperties = {transition=easing.Out, time=delay, onComplete=protected.transitionEnd}
				if(newY ~= nil) then
					transitionProperties.y = newY
					protected.transitioning = true
				end
				if(newX ~= nil) then 
					transitionProperties.x = newX
					protected.transitioning = true
				end
				
				transition.to( this.containerGroup, transitionProperties )
				
			end
			
			--if(y ~= nil) then trace("Object y = " .. y .. "Container height = " .. this.containerGroup.height) end
		end
		
		protected.validatePosition = function(newX, newY)
			trace("validatePosition >", "Camera")
			local okToPan = true
			
			if(public.restrict == "parent")then
				trace("validatePosition > restrict = parent", "Camera")
				local parentContainer = this.containerGroup.parent
				if(newX)then
					local leftEdge = 0
					local rightEdge = newX + (this.containerGroup.width * this.containerGroup.xScale )
					--trace("validatePosition > BEFORE > newX = " .. newX, "Camera")
					if( newX  > leftEdge )then
						newX = leftEdge
					elseif( rightEdge  < parentContainer.contentWidth )then
						newX = parentContainer.contentWidth - (this.containerGroup.width * this.containerGroup.xScale)
					end
					--trace("validatePosition > AFTER > newX = " .. newX, "Camera")
				end
				
				if(newY)then
					local topEdge = 0
					local bottomEdge = newY + (this.containerGroup.height * this.containerGroup.yScale ) - public.paddingBottom
					--trace("validatePosition > BEFORE > newY = " .. newY.. ", paddingBottom = " .. public.paddingBottom, "Camera")
					if(newY > topEdge)then
						newY = topEdge
					elseif( bottomEdge < parentContainer.contentHeight )then
						newY = parentContainer.contentHeight - (this.containerGroup.height * this.containerGroup.yScale) + public.paddingBottom
					end
					trace("validatePosition > AFTER > newY = " .. newY, "Camera")
				end
			end
			
			return newX, newY
		end
		
		protected.updateCamera = function(newX, newY)
			if(newX)then this.containerGroup.x = newX end
			if(newY)then this.containerGroup.y = newY end
		end
		
		
		protected.transitionEnd = function()
			protected.transitioning = false
		end
		
		return api
		
	end
	
	
	--[[
	================================================
	StringUtils Class
	================================================
	]]
	
	local StringUtils = function(target)
	
		local public = {}
		local protected = {}
		
		local super = Class.buildClass(target, public, protected)
		-- this is what makes the whole thing work, methods access 'this' which points to the sub class 'private', if an implementation is not found there, then
		-- it will go up to the base class
		local this = protected
		-- same goes for the public, we should always access public through api, this way it will look in the subclass first and then the super class
		local api = public
		
		-- Concat the contents of the parameter list,
		-- separated by the string delimiter (just like in perl)
		-- example: strjoin( {"Anna", "Bob", "Charlie", "Dolores"}, ", ")
		public.join = function(list, delimiter)
		
			local len = getn(list)
			if len == 0 then 
				return "" 
			end
			
			local string = list[1]
			
			for i = 2, len do 
				string = string .. delimiter .. list[i] 
			end
			
			return string
		end

		-- Split text into a list consisting of the strings in text,
		-- separated by strings matching delimiter (which may be a pattern). 
		-- example: strsplit("Anna, Bob, Charlie,Dolores", ",%s*")
		public.split = function(text, delimiter)
			local t, ll
			t={}
			ll=0
			if(#text == 1) then return {text} end
				while true do
					l=string.find(text,delimiter,ll,true) -- find the next d in the string
					if l~=nil then -- if "not not" found then..
						table.insert(t, string.sub(text,ll,l-1)) -- Save it in our array.
						ll=l+1 -- save just after where we found it for searching next time.
					else
						table.insert(t, string.sub(text,ll)) -- Save what's left in our array.
					break -- Break at end, as it should be, according to the lua manual.
				end
			end
			return t
		end
		
		
		return api
		
	end
	
	--[[
	================================================
	PhysicsState Class
	================================================
	]]
	
	local PhysicsState = function(target)
	
		local public = {}
		local protected = {}
		
		local super = Class.buildClass(target, public, protected)
		-- this is what makes the whole thing work, methods access 'this' which points to the sub class 'private', if an implementation is not found there, then
		-- it will go up to the base class
		local this = protected
		-- same goes for the public, we should always access public through api, this way it will look in the subclass first and then the super class
		local api = public
		
		public.physicsRunning = false
		
		public.start = function()
			physics.start()
			public.physicsRunning = true
		end
		public.pause = function()
			physics.pause()
			public.physicsRunning = false
		end
		public.stop = function()
			physics.stop()
			public.physicsRunning = false
		end

		
		return api
		
	end
	
	--[[
	================================================
	NumberUtils Class
	================================================
	]]
	
	local NumberUtils = function(target)
	
		local public = {}
		local protected = {}
		
		local super = Class.buildClass(target, public, protected)
		-- this is what makes the whole thing work, methods access 'this' which points to the sub class 'private', if an implementation is not found there, then
		-- it will go up to the base class
		local this = protected
		-- same goes for the public, we should always access public through api, this way it will look in the subclass first and then the super class
		local api = public
		
		public.hexToRGB = function (sValue)
		
			local r,g,b
			
			r = tonumber( string.sub(sValue, 1,2), 16 )
			g = tonumber( string.sub(sValue, 3,4), 16 )
			b = tonumber( string.sub(sValue, 5,6), 16 )
		
			return r,g,b
		end

		
		return api
		
	end
	
	--[[
	================================================
	LayoutManager Class
	================================================
	]]

	local LayoutManager = function(target)
		
		local public = {}
		local protected = {}
		
		local super = Class.buildClass(target, public, protected)
		-- this is what makes the whole thing work, methods access 'this' which points to the sub class 'private', if an implementation is not found there, then
		-- it will go up to the base class
		local this = protected
		-- same goes for the public, we should always access public through api, this way it will look in the subclass first and then the super class
		local api = public
		
		--[[

			* does the layout of any object within it's parent. accepted properties are
				- x, y, width and height ( absolute positioning and sizing )
				- left, right, top and bottom ( anchors and stretching )
				- widthPolicy, heightPolicy
					- 'expand' default for groups, takes all the space it can within the parent ( setting width/height overrides this and sets the policy to 'fixed'
					- 'fixed' uses the absolute size defined in width, height
					- 'actualSize' default for anything non-group uses the actual size of the object ( i.e. and Image )

		]]
		public.doLayout = function (object, objectDescriptor, parent, coordinatePolicy)
			
			if(coordinatePolicy == nil)then
				coordinatePolicy = "screen"
			end
			--trace("LayoutManager > doLayout > BEFORE > object = " .. object.id .. " x = " .. object.x .. ", y = " .. object.y .. ", width = " .. object.width .. ", height = " .. object.height, "LayoutManager")
			local parentWidth
			local parentHeight
			
			local widthPolicy = objectDescriptor.widthPolicy
			local heightPolicy = objectDescriptor.heightPolicy
			
			if(coordinatePolicy == "contentSize")then
				parentWidth = math.max(parent.width, parent.contentWidth)
				parentHeight = math.max(parent.height, parent.contentHeight)
			elseif(coordinatePolicy == "screen")then
				parentWidth = parent.contentWidth
				parentHeight = parent.contentHeight
			end
			
			trace("LayoutManager > doLayout > BEFORE >  " .. " parentWidth = " .. parentWidth .. ", parent.height = " .. parent.height, "LayoutManager")
			
			if(widthPolicy == nil) then 
				if(objectDescriptor.type == "group" or objectDescriptor.type == "splosive.objects.View" or objectDescriptor.baseType == "splosive.objects.View")then
					objectDescriptor.zeroBased = true
					widthPolicy = "expand"
				else
					widthPolicy = "actualSize"
				end
			end
			
			if(heightPolicy == nil) then 
				if(objectDescriptor.type == "group" or objectDescriptor.type == "splosive.objects.View" or objectDescriptor.baseType == "splosive.objects.View")then
					heightPolicy = "expand"
				else
					heightPolicy = "actualSize"
				end
			end
			
			
			if(objectDescriptor.rotation ~= nil) then
				object.rotation = objectDescriptor.rotation
			end
			
			if(objectDescriptor.draggable ~= nil) then
				object.draggable = objectDescriptor.draggable
			end
			
			if(objectDescriptor.alpha ~= nil) then
				object.alpha = objectDescriptor.alpha
			end
			
			if(objectDescriptor.visible ~= nil) then
				object.isVisible = objectDescriptor.visible
			end
			
			local xPos = objectDescriptor.x
			local yPos = objectDescriptor.y
			
			if(objectDescriptor.x == nil) then
				--trace("setting x to 0", "LayoutManager")
				xPos = 0
			end
			if(objectDescriptor.y == nil) then
				--trace("setting y to 0", "LayoutManager")
				yPos = 0
			end
			
			
			
			if(objectDescriptor.zeroBased == true) then
				object.x = xPos
				object.y = yPos
				trace("setting x and y zeroBased (".. object.x .. ", "..object.y ..")", "LayoutManager")
			else
				object.x = xPos + (object.width/2)
				object.y = yPos + (object.height/2)
				trace("setting x and y NON zero (".. object.x .. ", "..object.y ..")", "LayoutManager")
			end
			
			if(objectDescriptor.width ~= nil) then
				object.width = objectDescriptor.width
				object.contentWidth = objectDescriptor.width
				widthPolicy = "fixed"
			end
			if(objectDescriptor.height ~= nil) then
				object.height = objectDescriptor.height
				object.contentHeight = objectDescriptor.height
				heightPolicy = "fixed"
			end
			
			--[[
			]]
			if(widthPolicy == "expand") then
				--object.width = parentWidth - object.x
				object.contentWidth = parentWidth - object.x
			end
			if(heightPolicy == "expand") then
				--object.height = parentHeight - object.y
				object.contentHeight = parentHeight - object.y
			end
			
			if(objectDescriptor.verticalCenter ~= nil)then
				if(objectDescriptor.zeroBased == true) then
					object.y = parentHeight/2 - object.height/2 + objectDescriptor.verticalCenter
				else
					object.y = parentHeight/2 + objectDescriptor.verticalCenter
				end
			else
				if(objectDescriptor.top ~= nil and objectDescriptor.bottom ~= nil) then
					if(objectDescriptor.zeroBased == true) then
						object.y = objectDescriptor.top
						object.height =  objectDescriptor.bottom - objectDescriptor.top
					else
						object.y = objectDescriptor.top + (object.height/2)
						object.height =  objectDescriptor.bottom - objectDescriptor.top + (object.height/2)
					end
				else
					if(objectDescriptor.top ~= nil) then
						if(objectDescriptor.zeroBased == true) then
							object.y = objectDescriptor.top
						else
							object.y = objectDescriptor.top + (object.height/2)
						end	
					end
					if(objectDescriptor.bottom ~= nil) then
						if(objectDescriptor.zeroBased == true) then
							object.y = parentHeight - object.height - objectDescriptor.bottom
						else
							object.y = parentHeight - object.height - objectDescriptor.bottom + (object.height/2)
						end
					end
				end
			end
			
			if(objectDescriptor.horizontalCenter ~= nil)then
				if(objectDescriptor.zeroBased == true) then
					object.x = parentWidth/2 - object.width/2 + objectDescriptor.horizontalCenter
				else
					object.x = parentWidth/2 + objectDescriptor.horizontalCenter
				end
			else
				if(objectDescriptor.left ~= nil and objectDescriptor.right ~= nil) then
					if(objectDescriptor.zeroBased == true) then
						object.x = objectDescriptor.left
						object.width =  objectDescriptor.right - objectDescriptor.left
					else
						object.x = objectDescriptor.left + (object.width/2)
						object.width =  objectDescriptor.right - objectDescriptor.left + (object.width/2)
					end
				else
					if(objectDescriptor.left ~= nil) then
						if(objectDescriptor.zeroBased == true) then
							object.x = objectDescriptor.left
						else
							object.x = objectDescriptor.left + (object.width/2)
						end
					end
					if(objectDescriptor.right ~= nil) then
						if(objectDescriptor.zeroBased == true) then
							object.x = parentWidth - object.width - objectDescriptor.right
						else
							object.x = parentWidth - object.width - objectDescriptor.right + (object.width/2)
						end
					end
				end
			end
			
			trace("LayoutManager > doLayout > AFTER >  " .. " parentWidth = " .. parentWidth .. ", parent.height = " .. parent.height, "LayoutManager")
			--trace("LayoutManager > doLayout > AFTER > object = " .. object.id .. " x = " .. object.x .. ", y = " .. object.y .. ", width = " .. object.width .. ", height = " .. object.height, "LayoutManager")
			
			
		end
		
		return api
		
	end

	--[[
	================================================
	View Class
	================================================
	]]

	local View = function(target, public, protected, params)
		
		local layoutManager = self.LayoutManager
		local StringUtils = self.StringUtils
		local NumberUtils = self.NumberUtils
		local PhysicsState = self.PhysicsState
		local config = self.Config
		
		local super = Class.buildClass(target, public, protected)
		-- this is what makes the whole thing work, methods access 'this' which points to the sub class 'private', if an implementation is not found there, then
		-- it will go up to the base class
		local this = protected
		-- same goes for the public, we should always access public through api, this way it will look in the subclass first and then the super class
		local api = public
		
		this.super = super
		
		if(params and params.descriptor ~= nil)then
			params.descriptor.baseType = "splosive.objects.View"
		end
		
		protected.camera = self.Camera()
		protected.behaviors = {}
		protected.pendingBehaviors = {}
		protected.listeners = {}
		protected.displayObjects = {}
		protected.descriptors = {}
		protected.objectWrappers = {}
		public.coordinatePolicy = "screen"
		public.physicsEnabled = false
		
		this.objectToFollow = nil
		this.currentNoId = 1
		public.completed = false
		
		protected.params = params
		
		public.setVisible = function(value)
			public.mainGroup.isVisible = value
		end
		public.getVisible = function()
			return public.mainGroup.isVisible
		end
		
		public.getCamera = function()
			return this.camera
		end
		
		public.getObjectByName = function(name)
			return this.objectWrappers[name]
		end
		
		
		public.removeObject = function( object )
			trace("View > removeObject > =======================", "View-Object")
		
			for k,wrapper in pairs(protected.objectWrappers) do
				if(wrapper.object == object)then
					trace("View > removeObject > destroying wrapper " .. wrapper.type, "View-Object")
					wrapper.destroy()
					protected.objectWrappers[k] = nil
				end
			end
			
			for rk,displayObjArr in pairs(this.displayObjectsArray) do
				if(displayObjArr == object)then
					trace("View > removeObject > removing displayObj from array " .. rk, "View-Object")
					this.displayObjectsArray[rk] = nil
				end
			end
			
			-- remove the displayObjects from the display list and references to them
			for key,displayObj in pairs(this.displayObjects) do
				if(displayObj == object)then
					trace("View > removeObject > removing displayObj from hash " .. key, "View-Object")
					this.deactivateObjectBehaviors(displayObj)
					displayObj:removeSelf()
					this[key] = nil
					this.displayObjects[key] = nil
				end
			end
			
		end
		
		protected.deactivateObjectBehaviors = function(displayObj)
			if(displayObj.touch ~= nil)then
				displayObj.touch = nil
				displayObj:removeEventListener( "touch", displayObj )
			end
			if(displayObj.collision ~= nil)then
				displayObj.collision = nil
				displayObj:removeEventListener( "collision", displayObj )
			end
			if(displayObj.behaviors ~= nil)then
				for kb,behaviorContext in pairs(displayObj.behaviors) do
					this.removeFromEventSources(behaviorContext, displayObj )
				end
			end
			
			displayObj.behaviors = nil
			
		end
		
		protected.removeFromEventSources = function(behaviorContext, displayObj)
			if(behaviorContext.eventSources ~= nil)then
				for k,v in pairs(behaviorContext.eventSources) do
					if(displayObj == v)then
						behaviorContext.eventSources[k] = nil
					end
				end
			elseif(behaviorContext.eventSource ~= nil)then
				behaviorContext.eventSource = nil
			end
		end
		
		
		super.public.clean = function()
			trace("------------------------ View > clean", "View-Allocation")
			--this.background:removeSelf()
		
			-- remove all the listeners
			for listenKey,listenerInfo in pairs(this.listeners) do
				trace("removing listenerInfo " .. listenKey, "View-Listeners")
				listenerInfo.eventSource:removeEventListener(listenerInfo.eventName, listenerInfo.eventHandler)
			end
			
			-- deactivate all the behaviors
			for k,behavior in ipairs(protected.behaviors) do
				trace("deactivating behavior ".. behavior.type, "View-Behavior")
				behavior.deactivate()
			end
			
			
			-- destroy objectWrappers
			for k,wrapper in pairs(protected.objectWrappers) do
				local wrapper_id = wrapper.id
				if(wrapper_id == nil)then
					wrapper_id = "NO_ID"
				end
				trace("destroying wrapper " .. wrapper.type ..", id = ".. wrapper_id, "View-Object")
				wrapper.destroy()
			end
			
			-- remove the displayObjects from the display list and references to them
			for key,displayObj in pairs(this.displayObjects) do
				trace("removing displayObj " .. key, "View-Object")
				displayObj.behaviors = nil
				displayObj:removeSelf()
				this[key] = nil
			end
			
			
			
			this.behaviors = {}
			this.pendingBehaviors = {}
			this.listeners = {}
			this.displayObjects = {}
			this.displayObjectsArray = {}
			this.objectWrappers = {}
			this.descriptors = {}
			
			if(public.physicsEnabled)then
				trace("stopping physics...", "Physics")
				PhysicsState.stop()
			end
			
		end
		
		protected.setup = function()
			for k,behavior in ipairs(protected.behaviors) do
				trace("activating behavior " .. behavior.type, "View-Behavior")
				behavior.preactivate()
				behavior.activate()
			end
			
			for listenKey,listenerInfo in pairs(this.listeners) do
				trace("adding listenerInfo " .. listenKey, "View-Listeners")
				listenerInfo.eventSource:addEventListener(listenerInfo.eventName, listenerInfo.eventHandler)
			end
			
		end
		
		protected.viewReady = function()
		end
		
		-- this must be overriden by the subclass to generate the view from a table
		protected.getLayout = function()
			trace("View > getLayout", "View")
			return {
				objects={
				},
				behaviors={
				}
			}
		end
		
		
		protected.loadRemoteLayout = function(path)
			trace("View > loadRemoteLayout", "View")
			local layoutReady = this.layoutReady
			
			local function networkListener( event )
		        if ( event.isError ) then
	                trace( "Network error! Couldn't load " .. path, "View-Networking")
		        else
	                trace ( path .. " =  " .. event.response )
	                layoutReady( event.response )
		        end
			end
			 
			local t = os.date( '*t' )  -- get table of current date and time
			local noCache = "?noCache=" .. os.time( t )
			network.request( path .. noCache, "GET", networkListener )
		
		end
		
		
		protected.createViewFromRemoteLayout = function(path)
			this.loadRemoteLayout( config.remoteViewsBasePath .. path .. ".json" )
		end
		
		protected.layoutReady = function( rawData )
		
			local remoteViewData = JSON:decode( rawData )
			this.createView(public.mainGroup, remoteViewData)
			
			this.setup()
			this.viewReady()
			
		end
		
		
		protected.createView = function(group, viewData)
			trace("---------------------- View > createView", "View-Allocation")
			
			this.rawViewData = viewData
			this.currentNoId = 1
			this.listeners = {}
			protected.behaviors = {}
			protected.pendingBehaviors = {}
			this.displayObjects = {}
			this.displayObjectsArray = {}
			this.descriptors = {}
			this.objectToFollow = nil
			public.completed = false
			
			--dump(viewData)
			
			
			-- size the group to take the full content size
			--[[
			group.width = display.contentWidth
			group.height = display.contentHeight
			]]
			group.contentWidth = display.contentWidth
			group.contentHeight = display.contentHeight
			--trace("createView > " .. group.width .. ", " .. group.height .. "content = " .. group.contentWidth .. ", " .. group.contentHeight)
			
			--local backgroundDescriptor = {type="splosive.objects.Image", id="background", asset="background.png", x=0, y=0, bodyType="none"}
			--this.createObject(group, backgroundDescriptor)
			
			-- activate the view options
			if (viewData.options ~= nil) then
				if (viewData.options.physics == true) then
					PhysicsState.start()
					PhysicsState.pause()
					public.physicsEnabled = true
					--gx, gy = physics.getGravity()
					trace("staring physics..", "Physics")
				end
				
				if(viewData.options.coordinatePolicy)then
					public.coordinatePolicy = viewData.options.coordinatePolicy
				end
			end
			
			
			
			-- create the objects and lay them out
			for k,v in ipairs(viewData.objects) do
				this.createObject(group, v)
			end
			
			
			
			-- gather behaviors
			if (viewData.behaviors ~= nil) then
				for k,v in ipairs(viewData.behaviors) do
					local topLevelBehavior = this.createBehavior(v)
					if(topLevelBehavior)then
						this.behaviors[#this.behaviors + 1] = topLevelBehavior
					else
						trace("[WARNING] Invalid Behavior " ..  k, "View-Behavior")
					end
				end
			end
			
			if (viewData.options ~= nil) then
				if (viewData.options.physics == true) then
					PhysicsState.start()
				end
			end
			
		end
		
		--[[ createObject method]]
		protected.createObject = function(parent, objectDescriptor)
			
			if (objectDescriptor.type == nil and type(objectDescriptor) == "table" ) then
				objectDescriptor.type = "group"
			end
			
							-- set object id				
			if(objectDescriptor.id == nil)then
				objectDescriptor.id = objectDescriptor.type .. "_" .. this.currentNoId
				this.currentNoId = this.currentNoId + 1
			end
			
			local object = nil
			local objectWrapper = nil
			local objectFactory = nil
			local view = api -- api contains the public members (methods & properties) of this view ( for all intents and purposes it is the view )
			
			--special case for camera ( TODO make this splosive.Camera so that people can create their own cameras if they wish )
			if (objectDescriptor.type == "camera") then
				trace("Adding camera", "Camera")
				this.camera.setContainer(parent)
				this.camera.restrict = objectDescriptor.restrict
				
				this.camera.paddingLeft = objectDescriptor.paddingLeft or 0
				this.camera.paddingRight = objectDescriptor.paddingRight or 0
				this.camera.paddingTop = objectDescriptor.paddingTop or 0
				this.camera.paddingBottom = objectDescriptor.paddingBottom or 0
				
				this.camera.panTo(objectDescriptor.x, objectDescriptor.y)
			
			-- special case for groups ( groups are declared implicitly with a table containing other descriptors )
			elseif( objectDescriptor.type == "group" ) then
			
				object = display.newGroup()
				object.id = objectDescriptor.id			-- this is so the object itself knows its id
				
				layoutManager.doLayout(object, objectDescriptor, parent, public.coordinatePolicy)
				-- create the group's children
				for k,v in ipairs(objectDescriptor) do 
					local objectAdded = this.createObject(object, v)
				end
				
				
			else
				trace("View > createObject > " .. objectDescriptor.type .. ", id = " .. objectDescriptor.id, "View-Object-Create")
				
				objectFactory = config.getObjectFactory(this.createContext(objectDescriptor, parent))
				objectWrapper = objectFactory.create(view, parent)
				
				object = objectWrapper.object
				if(object)then
					object.id = objectDescriptor.id			-- this is so the object itself knows its id
				end
				
			end
			
			
			--============
			-- Post-processing object
			--============
			
			if(objectWrapper ~= nil)then
				this.objectWrappers[objectDescriptor.id] = objectWrapper -- this is a separate collection with all the objectWrappers created so we can call their destroy method later
				this.descriptors[objectDescriptor.id] = objectDescriptor
				
				this.addListeners(objectWrapper, objectDescriptor)
				
				-- These 2 might be nil under some circumstances ( certan wrappers don't return objects )
				this[objectDescriptor.id] = object		-- this is so that all the objects can be access through 'this' in the view 
				this.displayObjects[objectDescriptor.id] = object -- this is a separate collection with all the displayObjects created so we can remove them easily
				this.displayObjectsArray[#this.displayObjectsArray + 1] = object -- this is a separate collection with all the displayObjects created so we can remove them easily
			end
			
			if(object ~= nil) then
				object.descriptor = objectDescriptor
				
				parent:insert( object )
				layoutManager.doLayout(object, objectDescriptor, parent, public.coordinatePolicy)
				
				if(objectWrapper ~= nil)then
					objectWrapper.created()
				end
				return object
			end
			
			return nil
			
			
		end
		
		public.duplicateObject = function( object )
			if(object == nil) then 
				return nil
			end
			
			local objectDescriptor = object.descriptor
			
			
			if(objectDescriptor ~= nil)then
				objectFactory = config.getObjectFactory(this.createContext(objectDescriptor, parent))
				objectWrapper = objectFactory.create(api, object.parent)
				
				local newObject = objectWrapper.object
				if(newObject)then
					local newDescriptor = {}
					for k,v in pairs(objectDescriptor) do 
						newDescriptor[k] = v
					end
				
					newDescriptor.id = objectDescriptor.id .. "_copy"
				
					newObject.id = newDescriptor.id
					newObject.descriptor = newDescriptor
					--object.parent:insert( newObject )
					
					newObject.x = object.x
					newObject.y = object.y
					--newObject.alpha = object.alpha
					
					objectWrapper.created()
					
					return newObject
				end
			end
			
			
		end
		
		protected.dispatchEvent = function( event )
			event.target = public.mainGroup
			public.mainGroup:dispatchEvent( event )
		end
		
		public.addObject = function(object, parent)
			if(parent == nil)then
				parent = public.mainGroup
			end
			
			local objectDescriptor = object.descriptor
			trace("View > addObject " .. object.descriptor.id)
			this[objectDescriptor.id] = object
			this.displayObjects[objectDescriptor.id] = object
			this.displayObjectsArray[#this.displayObjectsArray + 1] = object
			
			parent:insert(object)
			
		end
		
		public.addWrapper = function(descriptor, wrapper)
			this.objectWrappers[descriptor.id] = wrapper
		end
		
		
		public.createObjectFromDescriptor = function(descriptor, parent, duplicate)
		
			if(parent == nil)then
				parent = public.mainGroup
			end
			
			if(duplicate == nil)then
				duplicate = false
			end
			
			local newDescriptor
			if(duplicate == true)then
				newDescriptor = public.duplicateDescriptor(descriptor)
			else
				newDescriptor = descriptor
			end
			
			
			local objectFactory = config.getObjectFactory(this.createContext(newDescriptor, parent))
			objectWrapper = objectFactory.create(api, parent)
			local object = objectWrapper.object
			object.descriptor = newDescriptor
			
			objectWrapper.created()
			
			return object, objectWrapper
		
		end
		
		
		public.duplicateDescriptor = function(descriptor, rename)
			if(rename == nil)then
				rename = true
			end
			
			local newDescriptor = {}
			for k,v in pairs(descriptor) do 
				trace("duplicateDescriptor > k = ".. k, "Editor")
				if(k == "item")then
					newDescriptor.item = public.duplicateDescriptor(v, false)
				else
					newDescriptor[k] = v
				end
			end
			
			if(descriptor.id and rename)then
				newDescriptor.id = descriptor.id .. "_copy"
			end
			return newDescriptor
		end
		
		public.addObjectFromDescriptor = function(descriptor, parent)
			if(parent == nil)then
				parent = public.mainGroup
			end
			
			trace("View > addObjectFromDescriptor " .. descriptor.id)
			
			object = public.createObjectFromDescriptor(descriptor, parent)
			
			if(object)then
				this[descriptor.id] = object
				this.displayObjects[descriptor.id] = object
				this.displayObjectsArray[#this.displayObjectsArray + 1] = object
				
				parent:insert(object)
			end
			
		end
		
		
		
		
		public.addBehavior = function(behaviorDescriptor, delay)
			if(delay == nil or delay == 0)then
				local topLevelBehavior = this.createBehavior(behaviorDescriptor)
				if(topLevelBehavior)then
					trace(behaviorDescriptor.type .. "created successfully")
					this.behaviors[#this.behaviors + 1] = topLevelBehavior
					topLevelBehavior.preactivate()
					topLevelBehavior.activate()
				else
					trace("[WARNING] Invalid Behavior " ..  behaviorDescriptor.type, "View-Behavior")
				end
			else
				this.pendingBehaviors[#this.pendingBehaviors + 1] = behaviorDescriptor
				timer.performWithDelay( delay, this.processPendingBehaviors )
			end
		end
		
		protected.processPendingBehaviors = function()
			for descK,descriptor in ipairs(protected.pendingBehaviors) do
				local topLevelBehavior = this.createBehavior(descriptor)
				if(topLevelBehavior)then
					trace(descriptor.type .. "created successfully")
					this.behaviors[#this.behaviors + 1] = topLevelBehavior
					topLevelBehavior.preactivate()
					topLevelBehavior.activate()
				else
					trace("[WARNING] Invalid Behavior " ..  descriptor.type, "View-Behavior")
				end
			end
			this.pendingBehaviors = {}
		end
		
		--[[ createBehavior method]]
		protected.createBehavior = function(behaviorDescriptor)
			local behavior
			
			-- make sure a type is defined, must be in the form of 'package.Behavior'
			if(behaviorDescriptor.type == nil)then
				return nil
			end
			
			behavior = config.getBehavior(behaviorDescriptor.type)

			if(behavior ~= nil)then
				local behaviorInstance = behavior( this.createContext(behaviorDescriptor) )
				return behaviorInstance
			end
			
			return nil
			
		end
		
		protected.addListeners = function(wrapper, descriptor)
			local object = wrapper.object
			if(object)then
				for k,v in pairs(descriptor) do 
					if(config.events[k] ~= nil )then
						this.listeners[#this.listeners + 1] = {eventSource=object, eventName=config.events[k], eventHandler=v}
					elseif(object.events ~= nil)then
						if(object.events[k] ~= nil )then
							trace("adding listener " .. k .. " to " .. descriptor.type, "View-Listeners")
							this.listeners[#this.listeners + 1] = {eventSource=object, eventName=object.events[k], eventHandler=v}
						end
					elseif(wrapper.events ~= nil)then
						if(wrapper.events[k] ~= nil )then
							trace("adding listener " .. k .. " to " .. descriptor.type, "View-Listeners")
							this.listeners[#this.listeners + 1] = {eventSource=object, eventName=wrapper.events[k], eventHandler=v}
						end
					end
				end	
			end
		end
		
		
		protected.getTarget = function(name)
			trace("getTarget > looking for : " ..name, "View-Get-Targets")
			local targetParts = StringUtils.split(name, ".")
			local currentObj = nil
			
			for k,v in pairs(targetParts) do
				trace("getTarget > " ..v, "View-Get-Targets")
				if(currentObj ~= nil)then
					trace("getTarget > currentObj exist", "View-Get-Targets")
					if(currentObj[v] ~= nil)then
						trace("getTarget > ".. v .." exists in currentObj", "View-Get-Targets")
						currentObj = currentObj[v]
					end
				else
					if(v == "View")then
						trace("getTarget > setting currentObj to this View", "View-Get-Targets")
						currentObj = api
					elseif(this.displayObjects[v] ~= nil)then
						trace("getTarget > ".. v .." is a displayObject", "View-Get-Targets")
						currentObj = this.displayObjects[v]
					elseif(this.objectWrappers[v] ~= nil)then
						trace("getTarget > ".. v .." is a objectWrappers", "View-Get-Targets")
						currentObj = this.objectWrappers[v]
					end
				end
			end
			
			return currentObj
				
		end
		
		protected.mapBehaviorContext = function(eventSourceObject, context)
			if(eventSourceObject ~= nil and context ~= nil)then
				if(eventSourceObject.behaviors == nil)then
					eventSourceObject.behaviors = {}
				end
				
				eventSourceObject.behaviors[#eventSourceObject.behaviors + 1] = context
			end
		end
		
		--[[ createContext method]]
		protected.createContext = function(descriptor, parent)
			local context = {}
			-- first make sure the behavior has a target and that its valid
			local singleTarget
			
			if(descriptor.target == nil)then
				trace("[WARNING] Behavior " .. descriptor.type .. " is missing a target", "View-Behavior")
			else
				singleTarget = this.getTarget(descriptor.target)
				if(singleTarget ~= nil)then
					context.target = singleTarget
				else
					error("Unable to find target " .. descriptor.target  .. " for Behavior " .. descriptor.type )
				end
			end
			
			if(descriptor.targets ~= nil)then
				local targetNames = StringUtils.split(descriptor.targets, ",")
				local targets = {}
				
				for k,v in pairs(targetNames) do
					local currentTarget = this.getTarget(v)
					if(currentTarget ~= nil)then
						targets[#targets + 1] = currentTarget
					else
						error("Unable to find target " .. v  .. " for Behavior " .. descriptor.type )
					end
				end
			
				context.targets = targets
			end
			
			-- if there is an event, make sure its valid
			if(descriptor.event ~= nil)then
				if(config.behaviorEvents()[descriptor.event] == nil )then
					error("Invalid event " .. descriptor.event .. " for behavior " .. descriptor.type)
				else
					context.event = descriptor.event
				end
			end
			
			
			if(descriptor.eventSources ~= nil)then
				local sourceNames = StringUtils.split(descriptor.eventSources, ",")
				local eventSources = {}
				
				for k,v in pairs(sourceNames) do
					trace("adding eventSource = " .. v, "View-Behavior")
					local currentEventSource = this.getTarget(v)
					if(currentEventSource ~= nil)then
						this.mapBehaviorContext(currentEventSource, context)
						eventSources[#eventSources + 1] = currentEventSource
					end
				end
			
				context.eventSources = eventSources
			end
			
			
			-- if there is an event, set the eventSource, if one is specified use it, otherwise assume it is the same as the target
			if(descriptor.eventSource ~= nil)then
				if(descriptor.eventSource == "Runtime") then
					context.eventSource = Runtime
				elseif(descriptor.eventSource == "View") then
					context.eventSource = api
				else
					local currentEventSource = this.getTarget(descriptor.eventSource)
					if(currentEventSource ~= nil)then
						this.mapBehaviorContext(currentEventSource, context)
						context.eventSource = currentEventSource
					else
						error("Unable to find eventSource " .. descriptor.eventSource  .. ", Behavior " .. descriptor.type )
					end
				end
			else	
				if(descriptor.event ~= nil)then
					context.eventSource = context.target
					this.mapBehaviorContext(context.target, context)
				end
			end
					
			local nestedBehaviors = {}
			
			if(descriptor.actions ~= nil)then
				for n,nestedB in ipairs(descriptor.actions) do 
					local nestedBehavior = this.createBehavior(nestedB)
					if(nestedBehavior)then
						nestedBehavior.activationPolicy = nestedB.activationPolicy or nestedBehavior.ACTIVATION_PARENT_EXECUTE
						nestedBehavior.executionPolicy = nestedB.executionPolicy or nestedBehavior.EXECUTION_PARENT_EXECUTE
						nestedBehaviors[#nestedBehaviors + 1] = nestedBehavior
					end
				end
			end
			
			if(parent ~= nil)then
				context.parent = parent
			end
			
			context.actions = nestedBehaviors
			context.currentView = api
			context.descriptor = descriptor
			
			return context
		end
		
		protected.init = function()
			-- build the view
			local mainGroup = display.newGroup()
			mainGroup.id = "view"
			local viewData = this.getLayout()
			this.createView( mainGroup,  viewData)
			public.mainGroup = mainGroup
			this.setup()
			this.viewReady()
			
		end
		
		protected.remoteInit = function( path )
			-- build the view
			local mainGroup = display.newGroup()
			mainGroup.id = "view"
			public.mainGroup = mainGroup
			
			this.createViewFromRemoteLayout(path)
			-- This 2 will be called after the layout is completely download it and built
			--this.setup()
			--this.viewReady()
		end
		
		return api
	end
	
	
--[[
================================================
End Main Package
================================================
]]

	self.NumberUtils = NumberUtils()
	self.PhysicsState = PhysicsState()
	self.StringUtils = StringUtils()
	self.Config = Config()
	self.IO = IO()
	self.Camera = Camera
	self.View = View
	self.newPlayer = Player
	self.LayoutManager = LayoutManager()
	self.ViewManager = ViewManager()
	self.dump = dump
	self.trace = trace

	return self
end


splosive = package()
